import { create } from 'zustand';
import { User, UserRole } from '@/types';
import { authApi } from '@/lib/api';
import { persist } from 'zustand/middleware';

interface AuthState {
  user: User | null;
  token: string | null;
  isLoading: boolean;
  error: string | null;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
  setUser: (user: User | null) => void;
  isAuthenticated: () => boolean;
}

const mapRoleToUserRole = (authority: string): UserRole => {
  switch (authority) {
    case 'ROLE_ADMIN':
      return UserRole.ADMIN;
    case 'ROLE_TEACHER':
      return UserRole.TEACHER;
    case 'ROLE_PARENT':
      return UserRole.PARENT;
    default:
      throw new Error('未知的用户角色');
  }
};

export const useAuth = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isLoading: false,
      error: null,
      login: async (username: string, password: string) => {
        set({ isLoading: true, error: null });
        try {
          const response = await authApi.login(username, password);
          const role = mapRoleToUserRole(response.roles[0].authority);
          
          const user: User = {
            id: username, // 临时使用 username 作为 id
            username: response.username,
            role,
            name: response.username, // 临时使用 username 作为 name
            email: '', // 后续补充
            phone: '', // 后续补充
            createdAt: new Date(),
            updatedAt: new Date(),
          };
          
          set({ 
            user,
            token: response.token,
            isLoading: false 
          });
        } catch (error) {
          set({ error: (error as Error).message, isLoading: false });
          throw error;
        }
      },
      logout: () => {
        authApi.logout();
        set({ user: null, token: null });
      },
      setUser: (user) => set({ user }),
      isAuthenticated: () => {
        return !!get().user;
      },
    }),
    {
      name: 'auth-storage',
    }
  )
); 